import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../controllers/webview_controller.dart';

class WebViewPage extends GetView<WebViewController> {
  const WebViewPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      // appBar: AppBar(
      //   title: Obx(() => Text(
      //     controller.title.value.isNotEmpty
      //       ? controller.title.value
      //       : '网页浏览',
      //     style: const TextStyle(fontSize: 16),
      //   )),
      //   backgroundColor: Colors.white,
      //   elevation: 0,
      //   leading: IconButton(
      //     icon: const Icon(Icons.arrow_back, color: Colors.black),
      //     onPressed: () => Get.back(),
      //   ),
      //   actions: [
      //     // 后退按钮
      //     Obx(() => IconButton(
      //       icon: Icon(
      //         Icons.arrow_back_ios,
      //         color: controller.canGoBack.value ? Colors.black : Colors.grey,
      //       ),
      //       onPressed: controller.canGoBack.value ? controller.goBack : null,
      //     )),
      //     // 前进按钮
      //     Obx(() => IconButton(
      //       icon: Icon(
      //         Icons.arrow_forward_ios,
      //         color: controller.canGoForward.value ? Colors.black : Colors.grey,
      //       ),
      //       onPressed: controller.canGoForward.value ? controller.goForward : null,
      //     )),
      //     // 刷新按钮
      //     IconButton(
      //       icon: const Icon(Icons.refresh, color: Colors.black),
      //       onPressed: controller.reload,
      //     ),
      //   ],
      // ),
      body: Stack(
        children: [
          // WebView
          InAppWebView(
            initialUrlRequest: URLRequest(
              url: WebUri(controller.initialUrl.isNotEmpty 
                ? controller.initialUrl 
                : 'https://www.baidu.com'),
            ),
            initialSettings: InAppWebViewSettings(
              // 隐藏滚动条
              verticalScrollBarEnabled: false,
              horizontalScrollBarEnabled: false,
              // 启用JavaScript
              javaScriptEnabled: true,
              // 允许混合内容
              mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
              // 允许文件访问
              allowFileAccessFromFileURLs: true,
              allowUniversalAccessFromFileURLs: true,
              // 启用DOM存储
              domStorageEnabled: true,
              // 启用数据库
              databaseEnabled: true,
              // 设置用户代理
              userAgent: 'GluzApp/1.0',
              // 启用缩放
              supportZoom: true,
              // 设置默认字体大小
              defaultFontSize: 16,
              // 启用硬件加速
              useWideViewPort: true,
              loadWithOverviewMode: true,
              // 允许不安全的内容
              allowsInlineMediaPlayback: true,
              // 允许混合内容
              allowsBackForwardNavigationGestures: true,
            ),
            onWebViewCreated: (InAppWebViewController webViewController) {
              controller.setWebViewController(webViewController);
              // 添加NativeBridge处理器 - 兼容原生Android/iOS的交互方式
              webViewController.addJavaScriptHandler(
                handlerName: 'NativeBridge',
                callback: (args) {
                  print('NativeBridge 处理器被调用，参数: $args');
                  if (args.isNotEmpty) {
                    final message = args[0].toString();
                    print('NativeBridge 消息: $message');
                    controller.handleNativeBridgeMessage(message);
                  } else {
                    print('NativeBridge 参数为空');
                  }
                },
              );
            },
            onLoadStart: (controller, url) {
              this.controller.onLoadStart();
              this.controller.updatePageInfo(url?.toString(), null);
            },
            onLoadStop: (controller, url) async {
              this.controller.onLoadStop();
              this.controller.updatePageInfo(url?.toString(), null);
              this.controller.updateNavigationState();
              
              // 注入自定义JavaScript
              await this.controller.injectCustomJavaScript();
              
              // 获取页面标题
              final title = await controller.getTitle();
              this.controller.updatePageInfo(null, title);

            },
            onReceivedError: (controller, request, errorResponse) {
              this.controller.onLoadStop();
              print('WebView加载错误: ${errorResponse?.description}');
            },
            onProgressChanged: (controller, progress) {
              // 可以在这里显示加载进度
              print('加载进度: $progress%');
            },
            onConsoleMessage: (controller, consoleMessage) {
              print('WebView控制台: ${consoleMessage.message}');
            },
          ),
          
          // 加载指示器
          Obx(() => controller.isLoading.value
            ? Container(
                color: Colors.white,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      LoadingAnimationWidget.staggeredDotsWave(
                        color: Colors.blue,
                        size: 50,
                      ),
                      const SizedBox(height: 20),
                      const Text(
                        '正在加载...',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }
} 